Repository navigation
Implement outbound email sending - #4
Conversation
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: defaults Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (3)
🚧 Files skipped from review as they are similar to previous changes (2)
📝 WalkthroughWalkthroughAdds a complete outbound email pipeline (validation, threading, provider send, persistence, oversized-body storage, and events), expands email event types, introduces test-harness fault injection and outbound tests, replaces a placeholder ORPC messages router with a send route, and converts many MVP doc items to struck-through. Changes
Sequence DiagramsequenceDiagram
participant Client
participant API as API Route\n(messages.ts)
participant Module as Outbound Module\n(outbound.ts)
participant DB as Database
participant Email as Provider\n(EMAIL)
participant Events as Event Queue\n(EMAIL_EVENTS)
participant Storage as R2 Storage\n(EMAIL_STORAGE)
Client->>API: POST /messages/send
API->>Module: sendMessage(userId, input)
Module->>Module: Validate input\n(recipient limits, body size)
Module->>DB: Resolve inbox ownership\n& find/create thread
DB-->>Module: Inbox + Thread info
rect rgba(100, 150, 200, 0.5)
Note over Module: Build message context\ncompute IDs, headers, reply context
Module->>Email: send(message with headers)
end
alt Success
Email-->>Module: providerMessageId
Module->>Storage: Put oversized body (if needed)
Storage-->>Module: Stored reference
Module->>DB: Insert message + update thread
DB-->>Module: Persisted
Module->>Events: Emit MessageSentAccepted
Events-->>Module: Queued
else Failure
Email-->>Module: Error
Module->>DB: Persist failure state with errorCode/message
DB-->>Module: Persisted
Module->>Events: Emit MessageSentFailed
Events-->>Module: Queued
end
Module-->>API: SendMessageResult
API-->>Client: 200 OK or error
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches
🧪 Generate unit tests (beta)
Comment |
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (1)
src/orpc/procedures/messages.ts (1)
16-25: Prefer a shared output schema here.
sendMessageResultSchemais hand-maintained whilesendMessage()defines the real payload. Exporting one schema from the outbound module keeps the oRPC contract from drifting the next time the send result changes. Based on learnings: Keep oRPC schema and handlers aligned when changing contracts.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/orpc/procedures/messages.ts` around lines 16 - 25, The sendMessageResultSchema defined here is duplicating the actual send result used by sendMessage(); stop hand-maintaining a separate schema and instead import/export the single shared output schema from the outbound module so the oRPC contract stays in sync. Replace the local sendMessageResultSchema with an import of the authoritative schema exported by the outbound code (the schema used by sendMessage()), update any references in this file to use that exported symbol, and export it if this module needs to re-expose the same name so callers continue to work.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@src/lib/email/outbound.ts`:
- Around line 133-243: Persist the outbound message before calling the
non-idempotent env.EMAIL.send: write the oversized body to EMAIL_STORAGE (if
bodyStorage.oversizedBodyR2Key), then inside database.transaction insert the
emailMessages row with status 'pending' (or 'sending'), null providerMessageId
and sentAt; after the transaction call env.EMAIL.send (the existing EMAIL.send
call), capture providerMessageId and map errors, then update the emailMessages
row (update providerMessageId, status='accepted' and sentAt on success or
status='failed' + errorCode/errorMessage on failure) and finally emit events
(env.EMAIL_EVENTS.send) based on the updated status; use the same
messageId/threadId/internetMessageId and reuse functions/symbols from this diff
(EMAIL.send, EMAIL_STORAGE.put, database.transaction, emailMessages
insert/update, createMessageSentAcceptedEvent/createMessageSentFailedEvent) so
retries won’t create duplicate outbound sends or leave missing local records.
- Around line 280-296: getReplyContext currently includes every
emailMessages.internetMessageId in the thread, which pulls in synthetic IDs for
failed outbound sends; change the database query that builds threadMessages to
exclude failed outbound rows by adding conditions on emailMessages.direction and
emailMessages.status (e.g., include rows where direction = 'inbound' OR
direction = 'outbound' AND status IN ('sent','accepted','delivered') or your
project's equivalent status flags) so only inbound or accepted/outgoing messages
contribute to references; update the mapping that builds references from
threadMessages.internetMessageId accordingly and add a regression test that
simulates a failed outgoing send and then a retry to ensure the retry does not
set In-Reply-To/References to the failed message ID.
---
Nitpick comments:
In `@src/orpc/procedures/messages.ts`:
- Around line 16-25: The sendMessageResultSchema defined here is duplicating the
actual send result used by sendMessage(); stop hand-maintaining a separate
schema and instead import/export the single shared output schema from the
outbound module so the oRPC contract stays in sync. Replace the local
sendMessageResultSchema with an import of the authoritative schema exported by
the outbound code (the schema used by sendMessage()), update any references in
this file to use that exported symbol, and export it if this module needs to
re-expose the same name so callers continue to work.
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: 39fa80f6-73a9-485e-a603-ee8999cf02d0
📒 Files selected for processing (6)
mvp.mdsrc/lib/email/events.tssrc/lib/email/outbound.test.tssrc/lib/email/outbound.tssrc/lib/email/test-harness.tssrc/orpc/procedures/messages.ts
There was a problem hiding this comment.
🧹 Nitpick comments (3)
.github/workflows/ci.yml (3)
3-4: Consider specifying PR event types for clarity.The
pull_requesttrigger without explicit types defaults toopened,synchronize, andreopened, which is typically sufficient. If this is intentional, no change needed. Otherwise, consider being explicit:on: pull_request: types: [opened, synchronize, reopened]🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In @.github/workflows/ci.yml around lines 3 - 4, The workflow's GitHub Actions trigger uses the generic pull_request event; update the on: pull_request block to explicitly declare desired event types (e.g., types: [opened, synchronize, reopened]) to make the trigger behavior explicit and avoid accidental runs—modify the pull_request configuration in the CI workflow so it includes a types list under pull_request.
6-10: Add a job timeout to prevent runaway workflows.Without a timeout, the job can hang indefinitely if a step stalls, consuming CI minutes.
⏱️ Proposed fix to add timeout
jobs: validate: runs-on: ubuntu-latest + timeout-minutes: 15 permissions: contents: read🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In @.github/workflows/ci.yml around lines 6 - 10, Add a timeout to the validate job to prevent runaway workflows by adding a timeout-minutes setting under the job definition for validate (the jobs: validate: block). Modify the validate job configuration to include a sensible timeout-minutes value (e.g., 30) so the workflow runner cancels the job if it exceeds that duration; ensure the timeout-minutes key is at the same indentation level as runs-on and permissions within the validate job.
30-34: Clarify the purpose of the migration list step.Running
db:migrate:listafterdb:migrateis confusing—if the intent is to verify no pending migrations remain, consider failing the step when migrations are still pending. Otherwise, if this is purely informational, consider moving it beforedb:migrateto show what will be applied, or remove it if it adds no value.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In @.github/workflows/ci.yml around lines 30 - 34, The "Check pending local migrations" step currently runs pnpm db:migrate:list after pnpm db:migrate but doesn't fail the job if migrations remain; change this step (named "Check pending local migrations") to explicitly verify there are no pending migrations and fail CI when there are: run pnpm db:migrate:list and exit non-zero if its output indicates pending migrations (or call a small script/npm script that parses pnpm db:migrate:list output and returns non-zero on pending items) so the pipeline enforces that pnpm db:migrate left the DB up-to-date.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Nitpick comments:
In @.github/workflows/ci.yml:
- Around line 3-4: The workflow's GitHub Actions trigger uses the generic
pull_request event; update the on: pull_request block to explicitly declare
desired event types (e.g., types: [opened, synchronize, reopened]) to make the
trigger behavior explicit and avoid accidental runs—modify the pull_request
configuration in the CI workflow so it includes a types list under pull_request.
- Around line 6-10: Add a timeout to the validate job to prevent runaway
workflows by adding a timeout-minutes setting under the job definition for
validate (the jobs: validate: block). Modify the validate job configuration to
include a sensible timeout-minutes value (e.g., 30) so the workflow runner
cancels the job if it exceeds that duration; ensure the timeout-minutes key is
at the same indentation level as runs-on and permissions within the validate
job.
- Around line 30-34: The "Check pending local migrations" step currently runs
pnpm db:migrate:list after pnpm db:migrate but doesn't fail the job if
migrations remain; change this step (named "Check pending local migrations") to
explicitly verify there are no pending migrations and fail CI when there are:
run pnpm db:migrate:list and exit non-zero if its output indicates pending
migrations (or call a small script/npm script that parses pnpm db:migrate:list
output and returns non-zero on pending items) so the pipeline enforces that pnpm
db:migrate left the DB up-to-date.
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/lib/email/inboxes.ts (1)
156-192:⚠️ Potential issue | 🟡 MinorPotential TOCTOU race condition in alias uniqueness check.
The check for existing alias (lines 171-184) and the subsequent update (lines 187-190) are not atomic. Under concurrent requests, two users could both pass the uniqueness check before either update completes, potentially resulting in duplicate aliases.
The database has a unique index on
customLocalPart(from schema), which will prevent actual duplicates at the DB level, but the current code would throw a less descriptive database constraint error rather than the friendlyInboxAliasConflictError.Consider wrapping the check and update in a transaction, or catching the unique constraint violation and re-throwing as
InboxAliasConflictError.🛡️ Suggested fix using transaction
export async function updateInboxAliasForUser( userId: string, inboxId: string, alias: string | null, ) { const nextDb = getDb() const inbox = await getInboxForUser(userId, inboxId) if (!inbox) { return null } const normalizedAlias = alias === null ? null : validateInboxAlias(alias) - if (normalizedAlias) { - const [existingAlias] = await nextDb - .select({ id: inboxes.id }) - .from(inboxes) - .where( - and( - eq(inboxes.customLocalPart, normalizedAlias), - ne(inboxes.id, inboxId), - ), - ) - .limit(1) - - if (existingAlias) { - throw new InboxAliasConflictError('That inbox alias is already taken.') + try { + if (normalizedAlias) { + const [existingAlias] = await nextDb + .select({ id: inboxes.id }) + .from(inboxes) + .where( + and( + eq(inboxes.customLocalPart, normalizedAlias), + ne(inboxes.id, inboxId), + ), + ) + .limit(1) + + if (existingAlias) { + throw new InboxAliasConflictError('That inbox alias is already taken.') + } } - } - - await nextDb - .update(inboxes) - .set({ customLocalPart: normalizedAlias }) - .where(and(eq(inboxes.userId, userId), eq(inboxes.id, inboxId))) + + await nextDb + .update(inboxes) + .set({ customLocalPart: normalizedAlias }) + .where(and(eq(inboxes.userId, userId), eq(inboxes.id, inboxId))) + } catch (error) { + // Handle unique constraint violation from race condition + if (error instanceof Error && error.message.includes('UNIQUE constraint failed')) { + throw new InboxAliasConflictError('That inbox alias is already taken.') + } + throw error + } return getInboxForUser(userId, inboxId) }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/lib/email/inboxes.ts` around lines 156 - 192, The uniqueness check and update in updateInboxAliasForUser (using getDb(), validateInboxAlias, getInboxForUser, and inboxes) must be made atomic: either perform the select-and-update inside a database transaction so the existence check and nextDb.update(...) occur together, or keep the current flow but catch the DB unique constraint error thrown by the update (the unique index on inboxes.customLocalPart) and re-throw it as InboxAliasConflictError('That inbox alias is already taken.'); ensure you reference the inboxes table and convert the DB constraint error to the friendly error before returning getInboxForUser.
♻️ Duplicate comments (1)
src/lib/email/outbound.ts (1)
273-289:⚠️ Potential issue | 🟠 MajorExclude failed outbound messages from reply references.
getReplyContextincludes all messages in the thread regardless of status. Failed outbound messages still have a syntheticinternetMessageId, so replies could reference a message the remote server never received, potentially breaking threading.Filter to only include successfully delivered messages:
🔧 Suggested fix
const threadMessages = await database .select({ internetMessageId: emailMessages.internetMessageId, + status: emailMessages.status, }) .from(emailMessages) .where(and(eq(emailMessages.threadId, threadId), eq(emailMessages.inboxId, inboxId))) .orderBy(asc(emailMessages.createdAt), asc(emailMessages.id)) const references = threadMessages + .filter((message) => message.status === 'received' || message.status === 'accepted') .map((message) => message.internetMessageId) .filter((value): value is string => Boolean(value))🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/lib/email/outbound.ts` around lines 273 - 289, getReplyContext is including messages regardless of delivery status so replies may reference synthetic internetMessageId values for failed outbound sends; update the query that builds threadMessages (the select from emailMessages filtered by threadId and inboxId) to exclude failed/undelivered messages by adding a status filter on emailMessages (e.g., only include statuses that indicate successful delivery such as "sent"/"delivered" or use a notIn([...failedStatuses]) condition), then build references from those filtered messages (still using emailMessages.internetMessageId, threadId, inboxId) so inReplyTo and references only point to actually delivered messages.
🧹 Nitpick comments (3)
src/lib/email/outbound.ts (1)
125-144: Consider persist-before-send for idempotency.The current flow calls
EMAIL.send()before persisting to the database. IfEMAIL.send()succeeds but a subsequent step (R2 write or DB transaction) fails, the email is delivered but no local record exists—client retries could duplicate the send.An alternative is to insert a
pendingrow first, attempt delivery, then update toaccepted/failed. This makes retries idempotent (check for existing pending/accepted row with same idempotency key). This is a tradeoff between complexity and resilience; flagging for consideration.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/lib/email/outbound.ts` around lines 125 - 144, The send flow currently calls env.EMAIL.send() before persisting the outbound record, which can lead to duplicate deliveries if the DB/R2 write fails; change the flow in outbound.ts to create a pending DB row first (with the same internetMessageId/idempotency key and fields used in buildOutboundHeaders/replyContext), then call EMAIL.send(), capture result.messageId into providerMessageId, and finally update the pending row status to 'accepted' or to 'failed' using the mapped error (mappedError.code / mappedError.message) on catch; ensure the update path is idempotent by checking for an existing pending/accepted row and using the internetMessageId/idempotency key to avoid double sends.src/lib/email/outbound.test.ts (1)
213-256: Consider adding a regression test for failed-send retry.The threading test validates
In-Reply-ToandReferencesheaders for successful sends. To guard against thegetReplyContextissue (failed sends leaking into references), consider adding a test that:
- Sends a message that fails at the provider
- Sends a successful reply
- Asserts the reply's
Referencesheader excludes the failed message'sinternetMessageId🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/lib/email/outbound.test.ts` around lines 213 - 256, Add a regression test that simulates a failed provider send and verifies reply headers don’t include the failed send’s internetMessageId: use sendMessage to create a first message but simulate a provider failure for that send (so it fails to set or persist internetMessageId), then send a successful reply via sendMessage with replyToThreadId set to the firstResult.threadId, query emailMessages for the successful reply and assert harness.email.sent for that reply does NOT include the failed message’s internetMessageId in References/In-Reply-To while still threading to the same threadId; reference sendMessage, getReplyContext (where the bug manifests), emailMessages, harness.email.sent, and internetMessageId to locate relevant logic to exercise and assert.src/lib/email/inboxes.ts (1)
8-29: Reserved aliases list includes appropriate entries.The reserved aliases cover standard email addresses (postmaster, abuse, support, etc.) and product-specific terms. Note that
koushikandkdawgappear to be personal reservations - consider documenting their purpose or moving them to configuration if they're user-specific.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/lib/email/inboxes.ts` around lines 8 - 29, RESERVED_INBOX_ALIASES currently contains two personal aliases ("koushik" and "kdawg"); remove these from the hard-coded Set and either document them or move them to a configurable source (env/config) so repository-wide reserved names are generic; update any references to RESERVED_INBOX_ALIASES to read from the new configuration or fallback to the existing Set without the personal entries, and add a brief comment explaining where personal/team-specific aliases should be configured.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Outside diff comments:
In `@src/lib/email/inboxes.ts`:
- Around line 156-192: The uniqueness check and update in
updateInboxAliasForUser (using getDb(), validateInboxAlias, getInboxForUser, and
inboxes) must be made atomic: either perform the select-and-update inside a
database transaction so the existence check and nextDb.update(...) occur
together, or keep the current flow but catch the DB unique constraint error
thrown by the update (the unique index on inboxes.customLocalPart) and re-throw
it as InboxAliasConflictError('That inbox alias is already taken.'); ensure you
reference the inboxes table and convert the DB constraint error to the friendly
error before returning getInboxForUser.
---
Duplicate comments:
In `@src/lib/email/outbound.ts`:
- Around line 273-289: getReplyContext is including messages regardless of
delivery status so replies may reference synthetic internetMessageId values for
failed outbound sends; update the query that builds threadMessages (the select
from emailMessages filtered by threadId and inboxId) to exclude
failed/undelivered messages by adding a status filter on emailMessages (e.g.,
only include statuses that indicate successful delivery such as
"sent"/"delivered" or use a notIn([...failedStatuses]) condition), then build
references from those filtered messages (still using
emailMessages.internetMessageId, threadId, inboxId) so inReplyTo and references
only point to actually delivered messages.
---
Nitpick comments:
In `@src/lib/email/inboxes.ts`:
- Around line 8-29: RESERVED_INBOX_ALIASES currently contains two personal
aliases ("koushik" and "kdawg"); remove these from the hard-coded Set and either
document them or move them to a configurable source (env/config) so
repository-wide reserved names are generic; update any references to
RESERVED_INBOX_ALIASES to read from the new configuration or fallback to the
existing Set without the personal entries, and add a brief comment explaining
where personal/team-specific aliases should be configured.
In `@src/lib/email/outbound.test.ts`:
- Around line 213-256: Add a regression test that simulates a failed provider
send and verifies reply headers don’t include the failed send’s
internetMessageId: use sendMessage to create a first message but simulate a
provider failure for that send (so it fails to set or persist
internetMessageId), then send a successful reply via sendMessage with
replyToThreadId set to the firstResult.threadId, query emailMessages for the
successful reply and assert harness.email.sent for that reply does NOT include
the failed message’s internetMessageId in References/In-Reply-To while still
threading to the same threadId; reference sendMessage, getReplyContext (where
the bug manifests), emailMessages, harness.email.sent, and internetMessageId to
locate relevant logic to exercise and assert.
In `@src/lib/email/outbound.ts`:
- Around line 125-144: The send flow currently calls env.EMAIL.send() before
persisting the outbound record, which can lead to duplicate deliveries if the
DB/R2 write fails; change the flow in outbound.ts to create a pending DB row
first (with the same internetMessageId/idempotency key and fields used in
buildOutboundHeaders/replyContext), then call EMAIL.send(), capture
result.messageId into providerMessageId, and finally update the pending row
status to 'accepted' or to 'failed' using the mapped error (mappedError.code /
mappedError.message) on catch; ensure the update path is idempotent by checking
for an existing pending/accepted row and using the internetMessageId/idempotency
key to avoid double sends.
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: 9c343db8-2155-48ea-ad6d-bf20c85e2a9e
📒 Files selected for processing (13)
src/db/client.tssrc/lib/auth.tssrc/lib/email/inbound.test.tssrc/lib/email/inbound.tssrc/lib/email/inboxes.test.tssrc/lib/email/inboxes.tssrc/lib/email/outbound.test.tssrc/lib/email/outbound.tssrc/lib/email/test-harness.test.tssrc/lib/runtime.tssrc/orpc/procedures/inboxes.tssrc/orpc/procedures/messages.tssrc/worker.ts
🚧 Files skipped from review as they are similar to previous changes (1)
- src/orpc/procedures/messages.ts
Summary
messages.sendpipeline with inbox ownership checks, payload validation, CloudflareEMAIL.send()delivery, thread linkage, and D1 persistence for accepted and failed outbound messagesmvp.mdto strike through the MVP items completed through the send pipelineValidation
Summary by CodeRabbit
New Features
API
Tests
Chores
Refactor
Documentation